package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.service.OrderPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 *
 * @since 2022/08/27 15:17
 * @author sunxuJ
 */
@Service
public class OrderPayServiceImpl implements OrderPayService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    StockMapper stockMapper;
    @Autowired
    OrderItemMapper orderItemMapper;

    @Transactional
    @Override
    public void paySuccess(String orderId) {
        //修改订单状态
        Order order = new Order();
        order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
        order.setUpdateTime(new Date());
        order.setOrderId(orderId);
        try {
            orderMapper.updateByPrimaryKeySelective(order);
        } catch (Exception e) {
            throw new BizException("220827","修改订单状态异常");
        }

        //修改库存
        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId", orderId);
        try {
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            for (OrderItem orderItem : orderItems) {
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();
                Stock stock = new Stock();
                stock.setItemId(itemId);
                stock.setStockCount((long)0);
                stock.setLockCount(-num);
                stockMapper.updateStock(stock);
            }
        } catch (Exception e) {
            throw new BizException("220828","修改库存异常");
        }

        //更新订单商品表状态
        Example example2 = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId", orderId);
        OrderItem orderItem = new OrderItem();
        orderItem.setStatus(3);
        orderItem.setUpdateTime(new Date());
        try {
            orderItemMapper.updateByExampleSelective(orderItem,example2);
        } catch (Exception e) {
            throw new BizException("220829","修改更新订单商品表状态异常");
        }

    }
}
